<script setup>
import { computed, ref, onMounted, reactive, watch } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { decodedAccessToken, get, proFileSet } from "@/net/index.js";
import noAvatar from '../../../public/img/noavatar_small.gif';

const route = useRoute();
const isEditing = ref(false); // 控制编辑表单的显示状态

const userRole = computed(() => {
  return decodedAccessToken().authorities
      .map(role => role.substring(5))
      .join(", "); // 用逗号和空格分隔
});

const formRef = ref();
const data = reactive({
  id: route.query.id,
  img: "",
  name: "",
  sex: "",
  birth: "",
  dataAccessible: false,
});

const backupData = reactive({}); // 用于备份编辑前的数据

function loadData(id) {
  get(`/api/auth/home?id=${id}`, (responseData) => {
    Object.assign(data, responseData);
    data.id = id; // 更新 data.id，以确保同步最新 id
    console.log("接收数据:", JSON.stringify(data, null, 2));
  }, () => {
    ElMessage.info("该用户已隐藏个人信息");
    data.dataAccessible = false;
  });
}

// 页面加载时获取用户数据
onMounted(() => {
  loadData(route.query.id);
});

// 监听查询参数 id 变化时刷新数据
watch(
    () => route.query.id,
    (newId) => {
      if (newId !== data.id) {
        loadData(newId);
      }
    }
);

// 编辑模式开启时备份数据
function editProfile() {
  isEditing.value = true;
  Object.assign(backupData, data);
}

// 保存表单数据
function saveProfile() {
  proFileSet(data, () => {
    isEditing.value = false;
  }, () => {
    ElMessage.error("保存失败，请重试");
  });
}

// 取消编辑，恢复备份数据
function cancelEdit() {
  Object.assign(data, backupData);
  isEditing.value = false;
}
</script>

<template>
  <div class="profile-container">
    <h1 class="profile-title">个人资料</h1>
    <div v-if="data.name" class="profile-details">
      <!-- 用户头像 -->

      <div class="profile-avatar">
        <img :src="data.img || noAvatar" alt="用户头像" />
      </div>

      <!-- 用户信息展示 -->
      <div v-if="!isEditing" class="profile-info">
        <el-descriptions
            column="1"
            label-position="left"
            label-width="120px"
            class="profile-descriptions"
        >
          <el-descriptions-item label="ID">{{ data.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ data.name }}</el-descriptions-item>
          <el-descriptions-item label="生日">{{ data.birth }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ data.sex }}</el-descriptions-item>
          <el-descriptions-item
              v-if="data.id==decodedAccessToken().id"
              label="权限"> {{ userRole }} </el-descriptions-item>
          <el-descriptions-item
              v-if="data.id==decodedAccessToken().id"
              label="是否隐藏个人信息">
            {{ data.dataAccessible ? "是" : "否" }}
          </el-descriptions-item>
        </el-descriptions>
        <el-button
            v-if="data.id==decodedAccessToken().id"
            @click="editProfile"
            type="primary"
            class="edit-button"
        >
          编辑个人资料
        </el-button>
      </div>

      <!-- 编辑表单 -->
      <div v-else class="edit-form">
        <el-form :model="data" ref="formRef" label-width="120px" class="form-layout">
          <el-form-item label="用户名:">
            <el-input v-model="data.name" placeholder="请输入用户名" />
          </el-form-item>

          <el-form-item label="生日:">
            <el-date-picker
                v-model="data.birth"
                type="date"
                placeholder="请选择生日"
                format="yyyy-MM-dd"
            />
          </el-form-item>

          <el-form-item label="性别:">
            <el-select v-model="data.sex" placeholder="请选择性别">
              <el-option value="男" label="男" />
              <el-option value="女" label="女" />
              <el-option value="其他" label="其他" />
            </el-select>
          </el-form-item>

          <el-form-item label="是否隐藏个人信息:">
            <el-switch v-model="data.dataAccessible" active-text="隐藏" inactive-text="显示" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="saveProfile">保存</el-button>
            <el-button @click="cancelEdit" type="default">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div v-else class="loading-text">加载中...</div>
  </div>
</template>
<style scoped>
/* 容器和标题 */
.profile-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 30px;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.profile-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  text-align: center;
  margin-bottom: 20px;
}

/* 用户头像样式 */
.profile-avatar img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e0e0e0;
}

/* 用户信息描述 */
.profile-info {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.profile-descriptions {
  width: 100%;
  font-size: 16px;
}

.profile-descriptions .el-descriptions-item__label {
  color: #555;
  font-weight: 500;
}

.profile-descriptions .el-descriptions-item__content {
  color: #333;
}

/* 按钮样式 */
.edit-button {
  margin-top: 15px;
  background-color: #409eff;
  color: #fff;
  border: none;
  padding: 8px 20px;
  font-size: 14px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.edit-button:hover {
  background-color: #66b1ff;
}

/* 编辑表单样式 */
.edit-form {
  width: 100%;
}

.edit-form .el-form-item__label {
  color: #666;
  font-weight: 500;
}

.el-input__inner,
.el-date-editor .el-input__inner,
.el-select .el-input__inner,
.el-switch {
  border-color: #dcdfe6;
  border-radius: 4px;
  transition: border-color 0.3s ease;
}

.el-input__inner:hover,
.el-date-editor .el-input__inner:hover,
.el-select .el-input__inner:hover {
  border-color: #c0c4cc;
}

/* 加载状态文本 */
.loading-text {
  color: #888;
  font-size: 16px;
  text-align: center;
  padding: 20px;
}
</style>




